import numpy as np
import cv2


PATH = './ball2.jpg'
img = None
aim_frame = None
HSV = [(0 , 102 , 81), (179 , 255 , 255)]
# # HSV = [(0,0,0),(0,0,0)] (0 , 160 , 94), (179 , 255 , 255)

def read():
    global img
    img=cv2.imread(PATH,cv2.IMREAD_UNCHANGED)
    cv2.namedWindow("master map", 0)
    cv2.resizeWindow("master map", 480, 600)
    cv2.imshow("master map",img)
    cv2.waitKey(0)
    


def normalize():
    #增强对比
    img = cv2.normalize(img,dst=None,alpha=350,beta=10,norm_type=cv2.NORM_MINMAX)
    cv2.namedWindow("enhancing contrast ratio ", 0)
    cv2.resizeWindow("enhancing contrast ratio ", 480, 600)
    cv2.imshow("enhancing contrast ratio ",img)
    cv2.waitKey(0)


def smoothness():
    #平滑
    result=cv2.blur(img,(5,5))
    cv2.namedWindow("smoothness", 0)
    cv2.resizeWindow("smoothness", 480, 600)
    cv2.imshow("smoothness",result)
    cv2.waitKey(0)


def binaryzation():
    #二值化
    global aim_frame
    img_2 = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    aim_frame = cv2.inRange(img_2, *HSV)
    cv2.namedWindow("binaryzation", 0)
    cv2.resizeWindow("binaryzation", 480, 600)
    cv2.imshow("binaryzation",aim_frame)
    cv2.waitKey(0)



def erode():
    #腐蚀
    dtf = cv2.erode(aim_frame, None, iterations=1)  
    cv2.namedWindow("corrosion", 0)
    cv2.resizeWindow("corrosion", 480, 600)
    cv2.imshow("corrosion",dtf)
    cv2.waitKey(0)



def dilate():
    #膨胀
    dtf = cv2.dilate(aim_frame, np.ones((3, 3), np.uint8), iterations=3)
    cv2.namedWindow("expansion", 0)
    cv2.resizeWindow("expansion", 480, 600)
    cv2.imshow("expansion",dtf)
    cv2.waitKey(0)



def outline():
    #轮廓
    contours, hierarchy = cv2.findContours(aim_frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    dts = cv2.drawContours(img, contours, -1,(0, 0, 255),cv2.FILLED)
    cv2.namedWindow("outline", 0)
    cv2.resizeWindow("outline", 480, 600)
    cv2.imshow("outline",dts)
    cv2.waitKey(0)


if __name__ == '__main__':
    read()
    smoothness()
    binaryzation()
    erode()
    dilate()
    outline()
    


